<?php
// @formatter:off
/**
 * @file s.users.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-08-22 23:54:04 +0000 (Thu, 22 Aug 2013) $
 *
 * $Id: s.users.php 103 2013-08-22 23:54:04Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0.0.1/services/s.users.php $
 */
// @formatter:on

$wcServiceStatus = false;
$wcServiceErrorCode = 500;

function SetInvalidParameters() {
	$wcServiceStatus = false;
	$wcServiceErrorCode = 500;
	$wcServiceErrorMsg = "This service was call with invalid parameters";
}
function SendEmail($to, $subject, $message) {
	global $wcSite;

	$subject = "wcomix: {$subject}";

	$headers[] = "From: {$wcSite["email"]}";
	$headers[] = "Reply-To: noreplay@{$_SERVER["SERVER_NAME"]}";
	$headers[] = "X-Mailer: PHP/".phpversion();
	$headers[] = "MIME-Version: 1.0";
	$headers[] = "Content-Type: text/html;";

	return mail($to, $subject, $message, implode("\r\n", $headers));
}
if(defined('__SERVICE__') && $wcProfile->allowedAny(WC_PERM_USER_REGISTER, WC_PERM_USER_LOGIN, WC_PERM_USER_EDIT, WC_PERM_USER_SELF_EDIT, WC_PERM_USER_ADMIN)) {
	/*
	 * Conditions for GET method:
	 *	- If there's is a user specified ($wcUser), the parameter
	 *	  "activate" is set and the requesting user is allowed to
	 *	  register, the service will attempt to active a pending account.
	 *
	 * Conditions for POST method:
	 *	- When there's a POST parameter called "MODE" set with the value
	 *	  "getusername", also a POST parameter called "EMAIL" and the
	 *	  requesting user is allowed to login, the service will send the
	 *	  mail address matching username through email.
	 *	- When there's a POST parameter called "MODE" set with the value
	 *	  "getpassword", a POST parameter called "USERNAME", also a POST
	 *	  parameter called "EMAIL" and the requesting user is allowed to
	 *	  login, the service will send a hash code to the matching user
	 *	  through email, so the user will be able to reset its password.
	 *	  This is basically because wcomix doesn't store password as plain
	 *	  text on the database.
	 *	- When there's a POST parameter called "MODE" set with the value
	 *	  "register", a POST parameter called CAPTCHA, a POST parameter
	 *	  called "USERNAME", a POST parameter called "PASSWORD", also a
	 *	  POST parameter called "EMAIL" and the requesting user is
	 *	  allowed to register, the service will insert the new user into
	 *	  the database and send a hash code to the new user through email
	 *	  to activate the account.
	 *	- When there's a POST parameter called "MODE" set with the value
	 *	  "password", a POST parameter called "USER" with a user id, a
	 *	  POST parameter called "PASSWORD", a POST parameter called
	 *	  "NEWPASSWORD", also a POST parameter called "HASH" and the
	 *	  requesting user is allowed to either edit users or self edit,
	 *	  the service will attempt to change the user's password.
	 *	- When there's a POST parameter called "MODE" set with the value
	 *	  "update", a POST parameter called "USER" with a user id, a POST
	 *	  parameter called "BASICS", a POST parameter called "DATA" and
	 *	  the requesting user is allowed to either edit users or self
	 *	  edit, the service will attempt update the user information.
	 *	- When there's a POST parameter called "MODE" set with the value
	 *	  "adm-update", a POST parameter called "USER" with a user id, a
	 *	  POST parameter called "GROUPS", and the requesting user is
	 *	  allowed to administer users, the service will attempt update
	 *	  user permission on groups.
	 */
	if($_SERVER["REQUEST_METHOD"] == "GET") {
		if($wcUser && isset($_REQUEST["activate"]) && $wcProfile->allowedTo(WC_PERM_USER_REGISTER)) {
			$hash = trim($_REQUEST["activate"]);

			if(!$wcUser->hash_register) {
				$wcServiceErrorMsg = "User is already activated";
			} elseif($wcUser->hash_register != $hash) {
				SetInvalidParameters();
			} else {
				$wcUser->hash_register = "";
				$wcUser->hash_dregister = 0;
				$wcServiceStatus = true;
			}
		} else {
			SetInvalidParameters();
		}
	} elseif($_SERVER["REQUEST_METHOD"] == "POST") {
		//
		// Loading global pointers.
		global $wcDefaults;
		global $wcCaptcha;

		if(isset($_POST["MODE"])) {
			if($_POST["MODE"] == "getusername" && isset($_POST["CAPTCHA"]) && isset($_POST["EMAIL"]) && $wcProfile->allowedTo(WC_PERM_USER_LOGIN)) {
				startCaptcha();

				$captcha = trim($_POST["CAPTCHA"]);
				$email = trim($_POST["EMAIL"]);
				$user = $wcUsersHolder->userByEmail($email);
				if($wcCaptcha->check($captcha) == false) {
					$wcServiceErrorMsg = "The security code entered was incorrect";
				} elseif($user && $user->ok()) {
					define("__EMAIL__", true);
					$wcAction = WC_EACTION_USERNAME;
					$wcThemeAssigns["TITLE"] = "Username Request";
					$wcThemeAssigns["USERID"] = $user->id;
					$wcThemeAssigns["USERNAME"] = $user->name();

					startTheme();

					$parser = $wcTheme->parser();
					$parser->massiveAssign($wcThemeAssigns);
					$parser->noWarnings();
					$parser->noSummary();

					if(SendEmail($email, "Username Request", $parser->parse())) {
						$wcServiceStatus = true;
					} else {
						$wcServiceErrorMsg = "Unable to send e-mail to '{$email}'";
					}
				} else {
					$wcServiceErrorMsg = "There is no user associated with the e-mail '{$email}'";
				}
			} elseif($_POST["MODE"] == "getpassword" && isset($_POST["CAPTCHA"]) && isset($_POST["USERNAME"]) && isset($_POST["EMAIL"]) && $wcProfile->allowedTo(WC_PERM_USER_LOGIN)) {
				startCaptcha();

				$captcha = trim($_POST["CAPTCHA"]);
				$username = trim($_POST["USERNAME"]);
				$email = trim($_POST["EMAIL"]);
				$user = $wcUsersHolder->userByEmail($email);
				if($wcCaptcha->check($captcha) == false) {
					$wcServiceErrorMsg = "The security code entered was incorrect";
				} elseif($user && $user->ok() && $username == $user->name()) {
					$wcThemeAssigns["HASH"] = $user->resetPassword();
					if($wcThemeAssigns["HASH"] !== false) {
						define("__EMAIL__", true);
						$wcAction = WC_EACTION_PASSWORD;
						$wcThemeAssigns["TITLE"] = "Password Request";
						$wcThemeAssigns["USERID"] = $user->id;
						$wcThemeAssigns["USERNAME"] = $user->name();

						startTheme();

						$parser = $wcTheme->parser();
						$parser->massiveAssign($wcThemeAssigns);
						$parser->noWarnings();
						$parser->noSummary();

						if(SendEmail($email, "Password Request", $parser->parse())) {
							$wcServiceStatus = true;
						} else {
							$wcServiceErrorMsg = "Unable to send e-mail to '{$email}'";
						}
					} else {
						$wcServiceErrorMsg = "Unable to reset password";
					}
				} else {
					$wcServiceErrorMsg = "There is no user associated with the e-mail '{$email}'";
				}
			} elseif($_POST["MODE"] == "register" && isset($_POST["CAPTCHA"]) && isset($_POST["USERNAME"]) && isset($_POST["PASSWORD"]) && isset($_POST["EMAIL"]) && $wcProfile->allowedTo(WC_PERM_USER_REGISTER)) {
				startCaptcha();

				$captcha = trim($_POST["CAPTCHA"]);
				$username = trim($_POST["USERNAME"]);
				$password = trim($_POST["PASSWORD"]);
				$email = trim($_POST["EMAIL"]);

				$euser = $wcUsersHolder->userByEmail($email);
				$uuser = $wcUsersHolder->itemByName($username);
				if($wcCaptcha->check($captcha) == false) {
					$wcServiceErrorMsg = "The security code entered was incorrect";
				} elseif($euser) {
					$wcServiceErrorMsg = "E-mail '{$email}' is been used by another user";
				} elseif($uuser) {
					$wcServiceErrorMsg = "Username '{$username}' is not available";
				} else {
					$user = $wcUsersHolder->create($username);
					if($user) {
						$user->setPassword($password);
						$user->data()->email = $email;

						define("__EMAIL__", true);
						$wcAction = WC_EACTION_REGISTER;
						$wcThemeAssigns["TITLE"] = "Sign Up Request";
						$wcThemeAssigns["HASH"] = $user->hash_register;
						$wcThemeAssigns["USERID"] = $user->id;
						$wcThemeAssigns["USERNAME"] = $user->name();

						startTheme();

						$parser = $wcTheme->parser();
						$parser->massiveAssign($wcThemeAssigns);
						$parser->noWarnings();
						$parser->noSummary();

						if(SendEmail($email, "Sign Up Request", $parser->parse())) {
							$wcServiceStatus = true;
						} else {
							$wcServiceErrorMsg = "Unable to send e-mail to '{$email}'";
						}
					} else {
						$wcServiceErrorMsg = "Unable to create user '{$username}'";
					}
				}
			} elseif($_POST["MODE"] == "password" && isset($_POST["USER"]) && isset($_POST["PASSWORD"]) && isset($_POST["NEWPASSWORD"]) && isset($_POST["HASH"]) && $wcProfile->allowedAny(WC_PERM_USER_EDIT, WC_PERM_USER_SELF_EDIT, WC_PERM_USER_RESET)) {
				$userid = trim($_POST["USER"]);

				if(($wcUser && ($userid == $wcUser->id() || $wcProfile->allowedTo(WC_PERM_USER_EDIT))) || ($wcProfile->allowedTo(WC_PERM_USER_RESET) && isset($_POST["HASH"]))) {
					$password = trim($_POST["PASSWORD"]);
					$newpassword = trim($_POST["NEWPASSWORD"]);
					$hash = trim($_POST["HASH"]);

					$user = $wcUsersHolder->item($userid);
					if($user && $user->ok()) {
						if(($hash && $user->hash_reset == $hash) || $user->checkPassword(md5($password))) {
							$wcServiceStatus = $user->setPassword($newpassword);
						} elseif($user->hash_reset != $hash) {
							$wcServiceErrorMsg = "Current hash doesn't match";
						} else {
							$wcServiceErrorMsg = "Current password doesn't match";
						}
					} else {
						$wcServiceErrorMsg = "Not valid user";
					}
				} else {
					$wcServiceErrorMsg = "You are not allowed to edit other users information";
				}
			} elseif($_POST["MODE"] == "update" && isset($_POST["USER"]) && isset($_POST["BASICS"]) && isset($_POST["DATA"]) && $wcProfile->allowedAny(WC_PERM_USER_EDIT, WC_PERM_USER_SELF_EDIT)) {
				$userid = trim($_POST["USER"]);

				if($userid == $wcUser->id() || $wcProfile->allowedTo(WC_PERM_USER_EDIT)) {
					$bData = $_POST["BASICS"];
					$xData = $_POST["DATA"];

					$user = $wcUsersHolder->item($userid);
					if($user && $user->ok()) {
						$wcServiceStatus = true;
						//
						// Updating user extra data.
						$data = $user->data();
						foreach($wcUserXData["_names"] as $name) {
							if(isset($xData[$name]) && $xData[$name] != $data->getExtra($name)) {
								$data->setExtra($name, $xData[$name]);
							}
						}
						//
						// Updating fullname
						if(isset($bData["FULLNAME"]) && $bData["FULLNAME"] != $data->fullname) {
							$data->fullname = $bData["FULLNAME"];
						}
						if(isset($bData["EMAIL"]) && $bData["EMAIL"] != $data->email) {
							$euser = $wcUsersHolder->userByEmail($bData["EMAIL"]);
							if($euser) {
								$wcServiceErrorMsg = "E-mail '{$bData["EMAIL"]}' is been used by another user";
								$wcServiceStatus = false;
							} else {
								$data->email = $bData["EMAIL"];
							}
						}
					} else {
						$wcServiceErrorMsg = "Not valid user";
					}
				} else {
					$wcServiceErrorMsg = "You are not allowed to edit other users information";
				}
			} elseif($_POST["MODE"] == "adm-update" && isset($_POST["USER"]) && isset($_POST["GROUPS"]) && $wcProfile->allowedTo(WC_PERM_USER_ADMIN)) {
				//
				// Checking that Read Only Mode is not activated.
				if(!$wcDefaults["read-only"]) {
					$userid = trim($_POST["USER"]);
					$gData = $_POST["GROUPS"];

					$user = $wcUsersHolder->item($userid);
					if($user && $user->ok()) {
						$db = WCConnection::Instance();
						$dbprefix = $wcDatabaseAccess["prefix"];

						$stmt = null;
						$stmtId = basename(__FILE__)."[adm-update]";
						if($db->has($stmtId)) {
							$stmt = $db->get($stmtId);
						} else {
							$query = "update  {$dbprefix}group_users\n";
							$query .= "set     rel_gu_profile = :profile\n";
							$query .= "where   rel_gu_group	= :gid\n";
							$query .= " and    rel_gu_user  = :uid";

							$stmt = $db->prepare($stmtId, $query);
						}

						$params = array(
							":uid" => $user->id(),
							":gid" => 0,
							":profile" => ""
						);
						foreach($gData as $gid => $profile) {
							$params[":gid"] = $gid;
							$params[":profile"] = $profile;
							@$stmt->execute($params);
						}

						$wcServiceStatus = true;
					}
				} else {
					$wcServiceErrorMsg = "ReadOnlyMode activated";
				}
			} else {
				SetInvalidParameters();
			}
		} else {
			SetInvalidParameters();
		}
	} else {
		$wcServiceErrorMsg = "This service doesn't work on {$_SERVER["REQUEST_METHOD"]} method";
	}
} else {
	$wcServiceErrorCode = 403;
	$wcServiceErrorMsg = "Unable to access service";
}
?>